package com.eveinfo.api;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.TimeZone;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public abstract class AbstractApiHandler<E extends ApiResponse> extends DefaultHandler {
	
	protected SimpleDateFormat sdf;

	protected String text;
	protected ApiError error;
	protected E response;

	public AbstractApiHandler() {
		sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
	}

	public E getParsedData() throws ApiException {
		if (error != null)
			throw new ApiException(error);
		return response;
	}

	@Override
	public void characters(char[] ch, int start, int length) throws SAXException {
		text = new String(ch, start, length);
	}

	@Override
	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
		String value = (!localName.equals("")) ? localName : qName;
		if (value.equals("error")) {
			error = new ApiError();
			error.setCode(Integer.parseInt(attributes.getValue("code")));
		} else if (value.equals("eveapi")) {
			response.setVersion(Integer.parseInt(attributes.getValue("version")));
		}
	}

	@Override
	public void endElement(String uri, String localName, String qName) throws SAXException {
		String value = (!localName.equals("")) ? localName : qName;
		if (value.equals("error")) {
			error.setError(text);
		} else if (value.equals("currentTime")) {
			try {
				response.setCurrentTime(sdf.parse(text));
			} catch (ParseException e) {
				error = new ApiError();
				error.setError(e.getMessage());
				e.printStackTrace();
			}
		} else if (value.equals("cachedUntil")) {
			try {
				response.setCachedUntil(sdf.parse(text));
			} catch (ParseException e) {
				error = new ApiError();
				error.setError(e.getMessage());
				e.printStackTrace();
			}
		}
	}
}
